import { defineStore } from 'pinia'
import { getCatalogue, getMenuCatalogue } from '@/apis/ttsa'
import useWxShare from '@/hooks/useWxShare'
import { useConfigStore } from "@/store/config"
import { isWechat } from '@/utils/client'

const timeStrToNumber = (str: string) => {
  const [h, m] = str.split(':')
  return parseInt(h) * 60 + parseInt(m)
}

export const timeNumberToStr = (n: number) => {
  const num = Math.round(n)
  const conver = n => n > 9 ? n : ('0' + n)
  return `${conver(Math.floor(num / 60))}:${conver(num % 60)}`
}
export interface Tree {
  id: string | number
  name: string
  parent_node: string | number
  pre_node: string | number
  next_node: string | number
  level: number
  total: number
  duration: number
  time_duration: string
  _time_duration: string
  is_catalogue: boolean
  children?: Tree[]
  node_type?: number
}

export const useTreeStore = defineStore({
  id: 'treeStore',
  state: () => ({
    content_id: null,
    node_type: null, // 播放节点类型
    node_id: null, // 播放节点信息
    current: null,
    contentIdList: [], // 章节ID
    chapter: 0, // 当前第几章
    menuData: [], // 菜单数据
    nowChapter: [], // 当前章节信息
    hiddenContentId: '', // 不在目录中章节ID
    st: null,
    progressValue: 0
  }),
  actions: {
    // 设置当前节点
    async setCurrent(node) {
      // 不在目录中的节点并且是菜单
      if (!this.contentIdList.includes(node.content) && node.is_catalogue) {
        if (this.hiddenContentId !== node.content) {
          this.deleteMenuData()
        }
        await this.addMenuData(node)
      } else if (this.hiddenContentId && this.hiddenContentId !== node.content) {
        // 切换其他章节后隐藏不在目录中的节点
        this.deleteMenuData()
      }
      if (node.content !== this.content_id) {
        this.content_id = node.content
      }
      this.node_type = node.process_type

      this.current = this.getNodeData(node) || node
      this.perGo()
      // 获取分享信息
      const config = useConfigStore()
      if (isWechat() && node.id !== this.node_id) {
        this.node_id = node.id
        await config.getShareConfig(node.id)
        useWxShare().handShare()
      }
    },
    // 添加目录内容
    async addMenuData(node) {
      const res = await getCatalogue({ content_id: node.content })

      this.hiddenContentId = node.content

      this.menuData.push({
        content_id: Number(res.content_id),
        content_name: res.content_name,
        node_tree: res.catalogue_node_data
      })
      this.contentIdList.push(node.content)
    },
    // 删除已添加的目录内容
    deleteMenuData() {
      this.menuData = this.menuData.filter((i) => i.content_id !== this.hiddenContentId)
      this.contentIdList = this.contentIdList.filter((i) => i !== this.hiddenContentId)
      this.hiddenContentId = ''
    },
    // 获取内容目录
    async getMenuCatalogue() {
      const res = await getMenuCatalogue()
      this.menuData = res
      this.contentIdList = res.map(i => i.content_id)
      this.nowChapter = res[0]?.node_tree
    },
    // 上一章节/下一章节
    goParentNode(type: string) {
      const isNext = type === 'next'
      // 首页或最后一页
      if ((this.chapter === 0 && !isNext) || (this.chapter + 1 === this.menuData.length && isNext)) {
        return
      }
      this.chapter = isNext ? this.chapter + 1 : this.chapter - 1
      this.nowChapter = this.menuData[this.chapter].node_tree
    },
    // 设置当前章节信息
    setNowChapter(contentId) {
      this.chapter = this.contentIdList.indexOf(contentId)
      this.nowChapter = this.menuData[this.chapter].node_tree
    },
    // 获取父节点
    getParent(node?) {
      if (this.menuData.length < 1) return []
      const nodeData = node || this.current
      const parent = []
      const fn = (arr) => {
        arr.forEach(item => {
          parent.push(item)
          if (item.id === nodeData.id) throw parent
          if (item.children) fn(item.children)
          parent.pop()
        })
      }
      try {
        fn(this.menuData)
        return parent
      } catch (e) {
        return parent
      }
    },
    // 获取当前章节节点之前的节点
    getBeforeNode(node?) {
      if (!this.current) return []
      const nodes = []
      const nowNode = node && node.id || this.current.id
      const fn = (arr) => {
        arr.forEach((item) => {
          if (item.id === nowNode) {
            nodes.push(item.id)
            throw nodes
          } else {
            nodes.push(item.id)
            item.children && fn(item.children)
          }
        })
      }
      try {
        fn(this.nowChapter)
        return nodes
      } catch (e) {
        return nodes
      }
    },
    // 获取节点
    getNodeData(node) {
      if (this.menuData.length < 1 || !node) return null
      let nodeData = null
      const fn = (arr) => {
        arr.forEach(item => {
          if (item.id === node.id) {
            throw nodeData = item
          }
          if (item.children) fn(item.children)
        })
      }
      const content = this.menuData.find(item => item.content_id === this.content_id)

      try {
        fn(content.node_tree)
        return nodeData
      } catch (e) {
        return nodeData
      }
    },
    perGo() {
      if (!this.current) return
      this.clearPerGo()
      const [startTimeStr] = this.current?.time_duration ? this.current?.time_duration.split('-') : ['00:00']
      // 开始时长
      const startTime = timeStrToNumber(startTimeStr)
      // 视频时长
      const videoTime = Math.ceil(this.current?.duration)
      this.progressValue = startTime
      this.st = setInterval(() => {
        this.progressValue += 1
        if (this.progressValue >= startTime + videoTime) {
          this.progressValue = startTime + videoTime
          this.clearPerGo()
        }
      }, 1000)
    },
    clearPerGo() {
      if (this.st) {
        clearInterval(this.st)
        this.st = null
      }
    }
  },
})
